<template>
    <div style="padding: 12px; box-sizing: border-box;">
        <el-dialog v-model="dialogVisible" :title="formData.id ? '菜单修改' : '菜单新增'" width="600px">
            <el-tabs tab-position="left" v-model="tabIndex" @tab-change="tabChange">
                <el-tab-pane :name="0" label="页面权限">
                    <el-form :inline="false" :model="formData" class="demo-form-inline">

                        <el-form-item label="父级路由">
                            <el-cascader v-model="formData.pid" :options="removeLeafNodes(tableData)" placeholder="父级路由"
                                :props="props" style="margin-right: 20px; width: 210px;" />(不填就是顶层)
                        </el-form-item>
                        <el-form-item label="菜单名称">
                            <el-input style="width: 210px;" v-model="formData.alias" placeholder="菜单名称" clearable />
                        </el-form-item>
                        <el-form-item label="路由名称">
                            <el-input style="width: 210px;" v-model="formData.name" placeholder="路由名称" clearable />
                        </el-form-item>
                        <!-- <el-form-item label="路由路径">
                            <el-input style="width: 210px;" v-model="formData.path" placeholder="路由名称" clearable />
                        </el-form-item> -->
                        <el-form-item label="路由次序">
                            <el-input-number style="width: 210px;" v-model="formData.order" :min="0" clearable />

                        </el-form-item>
                        <el-form-item label="是否菜单">
                            <el-radio-group v-model="formData.ism">
                                <el-radio :value="true" size="large">是</el-radio>
                                <el-radio :value="false" size="large">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="是否禁用">
                            <el-radio-group v-model="formData.disabled">
                                <el-radio :value="true" size="large">是</el-radio>
                                <el-radio :value="false" size="large">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="路由图标">
                            <!-- 为输入框添加点击事件，点击弹出图标选择弹窗 -->
                            <el-input style="width: 210px;" readonly v-model="formData.icon" placeholder="请选择路由图标"
                                clearable @click="showIconDialog = true" />
                            <component style="width: 30px;height: 30px;margin-left: 10px;color: #409eff;"
                                v-if="formData.icon" :is="formData.icon"></component>
                        </el-form-item>
                    </el-form></el-tab-pane>
                <el-tab-pane :name="1" v-if="formData.id && !formData.isMenu" label="按钮权限">
                    <el-space warp> <el-input style="width: 100px;" v-model="tagInfo.tagValue" placeholder="按钮名称"
                            clearable /><el-input style="width: 120px;" v-model="tagInfo.tagCode" placeholder="按钮权限标识"
                            clearable /><input type="color" style="height: 32px;" v-model="tagInfo.tagColor"> <el-button
                            type="primary" color="purple" @click="addBtnRole">{{ tagInfo.did ? '修改' : ' 新增'
                            }}</el-button></el-space>
                    <el-card style="margin-top: 10px;">
                        <template #header>
                            <div>
                                <el-table :data="roleTags" stripe style="width: 100%">
                                    <el-table-column prop="name" align="center" label="按钮名称">
                                        <template #default="scope">
                                            <div :style="{ color: scope.row.color }">{{ scope.row.name }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="code" align="center" label="按钮标识">
                                        <template #default="scope">
                                            <div :style="{ color: scope.row.color }">{{ scope.row.code }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" align="center"> <template #default="scope">
                                            <el-space wrap>
                                                <el-button size="small" @click="putbtn(scope.row._id, scope.row)"
                                                    type="primary">{{ scope.row._id == tagInfo.did ? '取消' : '编辑'
                                                    }}</el-button>
                                                <el-button size="small" @click="deletebtn(scope.row._id)"
                                                    type="danger">删除</el-button>
                                            </el-space>
                                        </template></el-table-column>

                                </el-table>
                            </div>
                        </template>
                    </el-card>

                </el-tab-pane>

            </el-tabs>

            <!-- 图标选择弹窗 -->
            <el-dialog v-model="showIconDialog" title="选择路由图标" width="1000px">
                <!-- 这里简单示例展示 Element Plus 图标，实际可按需调整 -->
                <div
                    style="width: 100%;height: 600px;overflow-y: scroll;display: flex;flex-wrap: wrap;justify-content: center;">
                    <template v-for="icon in Object.keys(ElIcon)">
                        <div class="icon-item" @click="selectIcon(icon)"
                            style="width: 60px;height: 60px;margin:10px 20px; display: flex;flex-direction: column; align-items: center;">
                            <component :is="icon"></component>
                            <div style="font-size: 12px;font-weight: bold;margin-top: 10px;"> {{ icon }}</div>
                        </div>


                    </template>
                </div>



            </el-dialog>

            <template #footer>
                <div>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button @click="onSubmit" type="primary">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-card style="width: 100%;">
            <template #header>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <span>菜单列表</span>
                    <el-button @click="handleForm()" type="primary">新增</el-button>
                </div>
            </template>
            <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" default-expand-all row-key="_id"
                border>

                <el-table-column align="center" prop="alias" label="菜单名称" />
                <el-table-column align="center" prop="name" label="路由名称" />
                              <!-- <el-table-column align="center" prop="path" label="路由路径" /> -->
                <el-table-column align="center" prop="isMenu" label="页面类型">
                    <template #default="scope">

                        <el-tag v-if="!scope.row.isMenu" type="primary">页面</el-tag>
                        <el-tag v-else type="success">菜单</el-tag>
                    </template>

                </el-table-column>
                <el-table-column align="center" prop="isMenu" label="是否禁用">
                    <template #default="scope">

                        <el-tag v-if="!scope.row.disabled" type="danger">未禁用</el-tag>
                        <el-tag v-else type="success">已禁用</el-tag>
                    </template>

                </el-table-column>
                <el-table-column align="center" prop="order" label="次序" />
                <el-table-column align="center" prop="icon" label="图标">
                    <template #default="scope">
                        <component style="width: 30px;height: 30px;margin-left: 10px;color: #409eff;"
                            v-if="scope.row.icon" :is="scope.row.icon"></component>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <template #default="scope">
                        <el-space wrap>
                            <el-button size="small" @click="handleForm(scope.row._id)" type="primary">编辑</el-button>
                            <el-button size="small" @click="deletem(scope.row._id)" type="danger">删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <template #footer>
                <div style="display: flex;justify-content: center;">
                    <el-pagination background layout="prev, pager, next" :total="1000" />
                </div>
            </template> -->
        </el-card>
        <sDialog ref="sdialog" :content="scontent" :confirmFunction="confirmFunction"></sDialog>
    </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue"
import { resetAble } from "@/composable/reset"
import { ElMessage } from "element-plus";
import { addmenu, getmenu, delmenu, getmenud, putmenu, } from "@/api/menu";
import { addbtnrole, getbtnrole, deletebtnrole, putbtnrole } from "@/api/menu";
import sDialog from "@/components/sDialog.vue";
import * as ElIcon from '@element-plus/icons-vue'
import { auth } from "@/api/login";

// import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance() as any
// const router = useRouter()

const showIconDialog = ref(false) // 控制图标选择弹窗的显示
const Iauth = () => {
    auth().then((res: any) => {
        if (res?.code == 200) {
        }
    }).catch((err: any) => {
        console.log(err, 'err')
    })

}
Iauth()
const scontent = ref('')
const confirmFunction = async () => {
    let res = await delmenu(handleItemId.value) as any
    if (res) {
        ElMessage({
            message: '操作成功',
            grouping: true,
            type: 'success',
        })
        init()
    }
}
const tableData = ref([])
const selectIcon = (icon: string) => {
    ElMessage({
        message: '已选择图标: ' + icon,
        grouping: true,
        type: 'success',
    })
    formData.value.icon = icon;
    showIconDialog.value = false;
};

const dialogVisible = ref(false)
const handleForm = async (id?: string) => {
    tabIndex.value = 0
    if (id) {
        let res = await getmenud({ id })
        formData.value = res.data
        formData.value.pid = res.data.parentId
        formData.value.id = id
        formData.value.ism = res.data.isMenu
    } else {

        reset()
    }
    dialogVisible.value = true
}


const tabChange = async () => {

    if (formData.value.id) {
        let res = await getbtnrole(formData.value) as any
        roleTags.value = res.data.btnRoles
    }
}
const { data: tagInfo, reset: tagReset } = resetAble({
    tagValue: '',
    tagColor: '#79bbff',
    tagCode: ''
}) as any

const putbtn = (id: string, item: any) => {


    if (id == tagInfo.value.did) {
        return tagReset()
    }

    tagInfo.value.tagColor = item.color
    tagInfo.value.tagValue = item.name
    tagInfo.value.tagCode = item.code
    tagInfo.value.did = id

    // let res=await 
}

const deletebtn = async (id: string) => {
    formData.value.did = id
    let res = await deletebtnrole(formData.value)
    if (res) {
        ElMessage({
            message: '操作成功',
            grouping: true,
            type: 'success',
        })
        tabChange()
    }
}
const tabIndex = ref(0)
const roleTags = ref<any>([])
const addBtnRole = async () => {
    let obj = {
        menuId: formData.value.id,
        color: tagInfo.value.tagColor,
        name: tagInfo.value.tagValue,
        code: tagInfo.value.tagCode,
    } as any
    if (!tagInfo.value.did && roleTags.value.map((e: any) => e.code).includes(obj.code)) {
        return ElMessage.error('已存在此按钮标识')
    } else {
        if (tagInfo.value.did) {
            let res = await putbtnrole({
                data: obj,
                did: tagInfo.value.did,
            })
            if (res) {
                ElMessage.success('修改成功')
                tabChange()
            }
        } else {
            let res = await addbtnrole(obj)
            if (res) {
                ElMessage.success('新增成功')
                tabChange()
            }
        }

    }
    tagReset()
}
const { data: formData, reset } = resetAble({
    name: '',
    pid: 0,
    id: "",
    alias: '',
    disabled: false,
    ism: true,
    path: '',
    order: 0
}) as any
const handleItemId = ref("")

const deletem = async (id: string) => {
    handleItemId.value = id
    proxy.$refs.sdialog.showCenterDialog = true
    scontent.value = '确定删除吗?'
}
const props = ref({
    value: '_id',
    label: 'alias',
    emitPath: false,
    checkStrictly: true,
})
const onSubmit = async () => {
    // formData.value.path = formData.value.name
    if (formData.value.id) {
        let res = await putmenu(formData.value) as any
        if (res) {
            init()
            ElMessage({
                message: '操作成功',
                grouping: true,
                type: 'success',
            })
        }
    } else {
        let res = await addmenu(formData.value) as any
        if (res) {
            init()
            ElMessage({
                message: '操作成功',
                grouping: true,
                type: 'success',
            })
        }
    }
    dialogVisible.value = false
}

const removeLeafNodes = (tree: any) => {
    // 递归函数：移除每个节点下的叶子节点
    const filterChildren = (nodes: any) => {
        if (!Array.isArray(nodes as any)) return [];
        return nodes
            .filter((node: any) => node.isMenu)
            .map((node: any) => ({
                ...node,
                children: filterChildren(node.children)
            }));
    };

    return filterChildren(tree);
};
const init = async () => {

    let res = await getmenu()
    if (res) {
        tableData.value = res.data
    }


}

init()
</script>
<style>
.icon-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.icon-item {
    width: 80px;
    height: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.icon-item:hover {
    background-color: #f5f7fa;
}

.active-icon {
    background-color: #e6f7ff;
    color: #1890ff;
}

.icon-name {
    font-size: 12px;
    margin-top: 6px;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
}
</style>